import pymysql

def connect_db(db_name):
    # print("连接到MySQL服务器。。。")
    db = pymysql.connect(host="localhost", user="root", password="root", db=db_name)
    # print("连接上了")
    return db

def create_table(db, table_name):
    cursor = db.cursor()
    cursor.execute("DROP TABLE IF EXISTS Movies")
    sql = """CREATE TABLE %s (
           id INT NOT NULL AUTO_INCREMENT,
           rating VARCHAR(255) NOT NULL,
           rank INT NOT NULL,
           cover_url VARCHAR(255) NOT NULL,
           movie_id INT NOT NULL,
         types VARCHAR(255) NOT NULL,
         regions VARCHAR(255) NOT NULL,
         title VARCHAR(50) NOT NULL,
           PRIMARY KEY (id),
           score FLOAT NOT NULL
           )""" % table_name
    cursor.execute(sql)

def insert_db(db,name,score):
    cursor = db.cursor()
    sql = """INSERT INTO Movies(name, score) VALUES ('%s', %f)""" % (name,score)
    try :
        cursor.execute(sql)
        db.commit()
    except:
        print("插入数据失败")
        db.rollback()



if __name__ == "__main__":
    conn = connect_db("movie")
    # print( conn)
    create_table(conn, "Movies")
    # insert_db(conn, "《唐顿庄园》", 9.5)
    # insert_db(conn, "《唐顿庄园2》", 9.0)